<template>
    <view class="content">
        <hx-navbar :config="config" />
        <view class="product" v-if="productInfo">
            <view class="product-box">
                <view class="order-content">
                    <view class="order-box">
                        <view class="order-box-cont">
                            <view>物料图片：</view>
                            <view>
                                <image src="/static/tianjia.png" mode="widthFix" class="btn-default-img"
                                    @click="chooseUploadMaterials(1)" />
                            </view>
                        </view>
                        <view style="display: flex;margin-bottom: 20rpx;">
                            <view style="width: 24%;"></view>
                            <view class="contract-url contract-url-image"
                                v-if="productInfo&& productInfo.upload_materials_image">
                                <view class="order-image" v-for="(item,index) in productInfo.upload_materials_image"
                                    :key="index">
                                    <image :src="item" @click="previewFile(item)"></image>
                                    <text @click="deleteImage(1, index)">删除</text>
                                </view>
                            </view>
                        </view>
                        <view class="order-box-cont">
                            <view>装箱图片：</view>
                            <view>
                                <image src="/static/tianjia.png" mode="widthFix" class="btn-default-img"
                                    @click="chooseUploadMaterials(2)" />
                            </view>
                        </view>
                        <view style="display: flex;margin-bottom: 20rpx;">
                            <view style="width: 24%;"></view>
                            <view class="contract-url contract-url-image"
                                v-if="productInfo&& productInfo.upload_packing_image">
                                <view class="order-image" v-for="(item,index) in productInfo.upload_packing_image"
                                    :key="index">
                                    <image :src="item" @click="previewFile(item)"></image>
                                    <text @click="deleteImage(2, index)">删除</text>
                                </view>

                            </view>

                        </view>
                        <view class="order-box-cont" style="align-items: center;">
                            <view>物流单号：</view>
                            <view>
                                <input class="uni-input" v-model="productInfo.tracking_number" focus
                                    placeholder="请输入物流单号" />
                            </view>
                        </view>
                        <view class="order-box-cont">
                            <view>物流单号图片：</view>
                            <view>
                                <image src="/static/tianjia.png" mode="widthFix" class="btn-default-img"
                                    @click="chooseUploadMaterials(3)" />
                            </view>
                        </view>
                        <view style="display: flex;margin-bottom: 40rpx;">
                            <view style="width: 24%;"></view>
                            <view class="contract-url contract-url-image"
                                v-if="productInfo&& productInfo.tracking_image">
                                <view class="order-image" v-for="(item,index) in productInfo.tracking_image"
                                    :key="index">
                                    <image :src="item" @click="previewFile(item)"></image>
                                    <text @click="deleteImage(3, index)">删除</text>
                                </view>
                            </view>
                        </view>
                        <view style="display: flex;">
                            <view style="width: 24%;"></view>
                            <view style="width: 25%;">
                                <button type="primary"
                                    style="width: 160rpx;height: 64rpx;text-align: center;line-height: 64rpx;font-size: 32rpx;"
                                    @click="shipmentSubClick">提交</button>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
        </view>
        <easy-watermark ref="waterMark" />
    </view>
</template>

<script>
    import {
        productInfoDetail,
        shipmentSub
    } from '@/common/api/order.js'
    import settings from '@/common/settings.js'
    export default {
        data() {
            return {
                config: {
                    back: true,
                    title: '发货',
                    color: '#ffffff',
                    //背景颜色;参数一：透明度（0-1）;参数二：背景颜色（array则为线性渐变，string为单色背景）
                    backgroundColor: [1, ['#6970ff', '#6970ff']],
                    // 状态栏 ，数组则为滑动变色
                    statusBarBackground: ['', '#ffffff'],
                },
                productInfo: [],
                textList: [
                    '拍摄时间: 2023年12月18日 10时28分27秒',
                ]
            }
        },

        onLoad(options) {
            this.orderProductInfoView(options.id)
        },
        methods: {
            shipmentSubClick() {
                if (!this.productInfo.upload_materials_image || (this.productInfo.upload_materials_image && this
                        .productInfo.upload_materials_image.length < 1)) {
                    uni.showToast({
                        title: '请上传物料图片',
                        icon: 'none'
                    });
                    return false;
                }
                if (!this.productInfo.upload_packing_image || (this.productInfo.upload_packing_image && this.productInfo
                        .upload_packing_image.length < 1)) {
                    uni.showToast({
                        title: '请上传装箱图片',
                        icon: 'none'
                    });
                    return false;
                }
                if ((!this.productInfo.tracking_image || (this.productInfo.tracking_image && this.productInfo
                        .tracking_image.length < 1)) && !this.productInfo
                    .tracking_number) {
                    uni.showToast({
                        title: '请上传物流单号或者物流单号图片',
                        icon: 'none'
                    });
                    return false;
                }
                shipmentSub(this.productInfo).then((res) => {
                    uni.navigateBack({
                        delta: 1 // 返回的页面层级，1 表示返回上一级页面
                    });
                }).catch((err) => {

                });

            },
            deleteImage(type, index) {
                if (type == 1) {
                    this.productInfo.upload_materials_image.splice(index, 1);
                }
                if (type == 2) {
                    this.productInfo.upload_packing_image.splice(index, 1);
                }
                if (type == 3) {
                    this.productInfo.tracking_image.splice(index, 1);
                }
            },
            uploadFile(type, tempFilePath) {
                if (!tempFilePath) {
                    console.error('没有选择图片');
                    return;
                }
                uni.uploadFile({
                    url: settings.baseUrl + '/api/backstage/fileUpload',
                    filePath: tempFilePath,
                    name: 'file',
                    formData: {
                        'type': 'image'
                    },
                    success: (res) => {
                        // 将JSON字符串转为对象
                        const result = JSON.parse(res.data);
                        // 检查接口返回是否成功
                        if (result.code === 200 && result.data && result.data.path) {
                            if (type == 1) {
                                // 将图片路径添加到数组中，实现页面实时显示
                                this.productInfo.upload_materials_image.push(result.data.path);
                            }
                            if (type == 2) {
                                // 将图片路径添加到数组中，实现页面实时显示
                                this.productInfo.upload_packing_image.push(result.data.path);
                            }
                            if (type == 3) {
                                // 将图片路径添加到数组中，实现页面实时显示
                                this.productInfo.tracking_image.push(result.data.path);
                            }
                        } else {
                            uni.showToast({
                                title: '上传失败：' + (result.msg || '未知错误'),
                                icon: 'none'
                            });
                        }
                    },
                    fail: (err) => {
                        console.error('文件上传失败：', err);
                    }
                });

            },
            /**
             * 获取当前时间
             */
            getNowTime() {
                var date = new Date(),
                    year = date.getFullYear(),
                    month = date.getMonth() + 1,
                    day = date.getDate(),
                    hour = date.getHours() < 10 ? "0" + date.getHours() : date.getHours(),
                    minute = date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes(),
                    second = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
                month >= 1 && month <= 9 ? (month = "0" + month) : "";
                day >= 0 && day <= 9 ? (day = "0" + day) : "";
                return (year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second);
            },
            chooseUploadMaterials(type) {
                // 使用 chooseImage 代替 chooseFile
                const waterMark = this.$refs.waterMark
                uni.chooseImage({
                    count: 1, // 最多选择1张图片
                    sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图
                    sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机
                    success: async e => {
                        uni.showLoading({
                            title: '图片处理中'
                        })
                        const url = e.tempFilePaths[0]
                        const path = await waterMark.addWatermark(url, [this.getNowTime()])
                        uni.hideLoading()
                        this.uploadFile(type, path);
                    },
                    fail: (err) => {
                        console.error('选择图片失败：', err);
                    }
                });
            },
            orderProductInfoView(id) {
                productInfoDetail({
                    id: id
                }).then((res) => {
                    this.productInfo = res
                    console.log(this.productInfo.upload_materials_image)
                }).catch((err) => {

                });
            },

            // 从URL中提取文件类型（根据后缀名）
            getFileTypeFromUrl(url) {
                if (!url) return null;
                // 匹配URL中最后一个"."后的字符串（忽略参数）
                const match = url.match(/\.([a-zA-Z0-9]+)(\?.*)?$/);
                if (match && match[1]) {
                    const ext = match[1].toLowerCase(); // 转为小写（兼容大小写后缀，如.PDF/.XLSX）
                    // 只保留我们需要的类型（pdf/xlsx/xls）
                    if (['pdf', 'xlsx', 'xls', 'jpg', 'png', 'jpeg'].includes(ext)) {
                        return ext;
                    }
                }
                return null; // 无法识别的类型
            },

            // 通用文件预览（基于URL后缀判断类型）
            previewFile(fileUrl) {
                if (!fileUrl) {
                    uni.showToast({
                        title: '暂无文件',
                        icon: 'none'
                    });
                    return;
                }

                // 1. 通过 URL 获取文件类型
                const fileType = this.getFileTypeFromUrl(fileUrl);
                if (!fileType) {
                    uni.showToast({
                        title: '不支持的文件类型',
                        icon: 'none'
                    });
                    return;
                }

                // 区分文件类型处理
                if (['png', 'jpg', 'jpeg'].includes(fileType)) {
                    // 图片类型，使用 uni.previewImage 预览
                    uni.previewImage({
                        urls: [fileUrl], // 图片预览接口要求传入数组，这里单个图片也用数组形式
                        success: (res) => {
                            console.log(`${fileType} 预览成功`, res);
                        },
                        fail: (err) => {
                            console.error(`${fileType} 预览失败`, err);
                            uni.showToast({
                                title: `打开图片失败`,
                                icon: 'none'
                            });
                        }
                    });
                } else {
                    // 文档类型，走原来的下载 + 打开流程
                    // 2. 下载文件（与之前逻辑一致）
                    uni.downloadFile({
                        url: fileUrl,
                        success: (downloadRes) => {
                            if (downloadRes.statusCode === 200) {
                                // 3. 打开文件（使用解析出的类型）
                                uni.openDocument({
                                    filePath: downloadRes.tempFilePath,
                                    fileType: fileType,
                                    showMenu: true,
                                    success: () => {
                                        console.log(`${fileType} 打开成功`);
                                    },
                                    fail: (err) => {
                                        console.error(`打开${fileType}失败`, err);
                                        uni.showToast({
                                            title: `打开文件失败`,
                                            icon: 'none'
                                        });
                                    }
                                });
                            } else {
                                uni.showToast({
                                    title: '文件下载失败',
                                    icon: 'none'
                                });
                            }
                        },
                        fail: () => {
                            uni.showToast({
                                title: '网络请求失败',
                                icon: 'none'
                            });
                        }
                    });
                }
            }
        }
    }
</script>

<style>
    page {
        background: #f5f5f5;
    }

    .content {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .product {
        display: flex;
        flex-direction: column;
        width: 100%;

    }

    .order-info {
        width: 100%;
        margin-top: 20rpx;
    }

    .product-box {
        background: #fff;
        margin: 10rpx 20rpx;
        display: flex;
        flex-direction: column;
        border-radius: 10rpx;
        padding: 20rpx;
    }

    .order-content {
        display: flex;
        justify-content: space-between;
        font-size: 20rpx;
    }

    .order-box {
        display: flex;
        flex-direction: column;
        width: 100%;
    }

    .order-box-cont {
        display: flex;
        margin-bottom: 20rpx;
    }

    .order-box-cont view:first-of-type {
        width: 24%;
        text-align: right;
    }

    .order-box-cont view:last-of-type {
        width: 70%;

    }

    .order-option {
        display: flex;
        justify-content: flex-end;
    }

    .order-btn {
        padding: 6rpx 30rpx;
        font-size: 20rpx;
        border: 1rpx solid #d5d5d5;
        border-radius: 30rpx;
        margin-left: 10rpx;
    }


    .order-btn-check {
        color: #aaaa00;
        border-color: #aaaa00;
    }

    .order-btn-sc {
        color: #00aaff;
        border-color: #00aaff;
    }

    .order-line {
        border-top: 1rpx solid #f5f5f5;
        margin: 15rpx 0;
    }


    .contract-url {
        width: 75%;
    }

    .contract-url view {
        display: flex;
        flex-direction: column;
    }

    .contract-url-cont text:first-of-type {
        width: 100%;
    }

    .contract-url-image {
        display: flex;
        flex-direction: row;
        flex-wrap: wrap;
    }

    .order-image {
        margin: 0 10rpx 10rpx 0;
        width: 80rpx;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
    }

    .order-image image {
        width: 80rpx;
        height: 80rpx;
    }

    .order-image text {
        width: 80rpx;
        text-align: center;
        color: red;
        border: 1rpx solid red;
        padding: 5rpx 0;
        border-radius: 7rpx;
        margin-top: 5rpx;
    }


    .btn-default-img {
        width: 60rpx;
        height: 60rpx;
        margin-right: 10rpx;
    }

    .uni-input {
        border-bottom: 1rpx solid #f1f1f1;
        padding: 5rpx;

    }
</style>